package com.cenluan.session;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.render.JavascriptRender;
import com.jfinal.render.JsonRender;
import com.jfinal.render.Render;
import com.jfinal.render.TextRender;

/**
 * session转视图拦截器，手动把session里的一些数据放入request，使视图中可以操作
 * 
 * @author peak
 * 
 */
public class SessionInViewInterceptor implements Interceptor {

	public void intercept(ActionInvocation ai) {
		ai.invoke();
		Controller controller = ai.getController();
		Render render = controller.getRender();
		// 如果渲染的是json，text或者javascript，不要把session数据带入视图
		if (render instanceof JsonRender || render instanceof TextRender
				|| render instanceof JavascriptRender) {
			return;
		}
		HttpSession session = controller.getSession();
		if (session == null) {
			return;
		}
		Map<String, Object> sessionMap = new HashMap<String, Object>();
		controller.setAttr("session", sessionMap);
		Enumeration<String> names = session.getAttributeNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			sessionMap.put(name, session.getAttribute(name));
		}

	}

}
